<!--  -->
<template>
  <div :class="className">
    <!--地图静态-->
    <div v-html="css"></div>
    <div :id="`wrapper${id}`" class="wrapper"></div>
    <div class="cover-view">
      <div class="container">
        <div class="flex-wrp">
          <div :class="{ activeTab: activeTab == index }" class="flex-item" v-for="(item, index) in tabArr" @click.stop="catchTap(item, index)" :key="index">
            <img :src="item.iconPath" mode="widthFix" />
            <div>{{ item.name }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
const css = function() {
  const { map_height,isfullScreen } = this.datas;

  return `
        .component-${this.id} .wrapper {
            width: ${this.fun.getPhoneEnv() == 3 ? "375" : this.map_width}px;
            height: ${isfullScreen ? map_height + 'px' : '100vh'};
        }
    `;
};
var infoWindow = null;
export default {
  props: ["id", "datas", "styles"],
  data() {
    return {
      map_width: "375",
      map: null,
      marker: null,
      tabArr: [],
      activeTab: null
    };
  },

  activated() {},

  components: {},

  computed: {
    css() {
      return "<style>" + css.call(this) + "</style>";
    },
    className() {
      const name = ["component-wrapper", `component-${this.id}`];
      return name;
    }
  },
  created() {
    //标注文字上的点击事件
    window.addressButton = e => {
      let position = e.split(",");
      // console.log(e,position);
      let point = { lng: Number(position[1]), lat: Number(position[0]) };
      this.fun.goToWXAdress(point);
    };
    window.toPage = e => {
      console.log(e);
      window.location.href = e;
    };
  },

  mounted() {
    this.map_width = document.body.clientWidth;
    this.initMap();
  },
  destroyed() {
    // 销毁地图，并清空地图容器.该方法执行后，地图对象被注销，内存释放，地图容器被清空。
    try {
      this.map.destroy();
    } catch (error) {
      console.log("map destroy error：：", error);
    }
  },
  methods: {
    initMap() {
      this.map = new AMap.Map(`wrapper${this.id}`, {
        resizeEnable: true,
        // center: [116.397428, 39.90923],
        zoom: 13
      });

      this.map.clearMap(); // 清除地图覆盖物
      let markers = this.transformArr(this.datas.list);
      infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
      var gmarker;
      this.markers = [];
      // 地图上添加点标记
      markers.forEach(marker => {
        gmarker = new AMap.Marker({
          map: this.map,
          icon: marker.iconPath,
          position: [marker.longitude, marker.latitude],
          offset: new AMap.Pixel(-13, -30),
          extData: {
            id: Number(marker.tabID)
          }
        });

        gmarker.content =
          '<p class="line-clamp-1" style="width: 140px; font-size: 14px;font-weight: bold;">' +
          marker.callout.content +
          "</p>" +
          '<p class="line-clamp-2" style="max-width: 130px;font-size: 11px;">' +
          marker.callout.text +
          "</p>" +
          '<div class="btn-box"><strong class="btn" style="margin-right: 12px;" onclick="addressButton(\'' +
          marker.latitude +
          "," +
          marker.longitude +
          '\')">到这里</strong><strong class="btn" onclick="toPage(\'' +
          marker.callout.link +
          "')\">详情</strong></div>";
        gmarker.on("click", this.markerClick);
        gmarker.emit("click", { target: gmarker });
        // gmarker.setExtData({longitude: marker.longitude,latitude: marker.latitude}); //给标注添加信息，点击时可以获取

        gmarker.setLabel({
          // offset: new AMap.Pixel(20, 20), //设置文本标注偏移量
          content: `<div class='info'>${marker.callout.content}</div>`, //设置文本标注内容
          direction: "top" //设置文本标注方位
        });

        this.markers.push(gmarker);
      });

      this.map.setFitView(); //标记点移到窗口内
    },
    markerClick(e) {
      infoWindow.setContent(e.target.content);
      infoWindow.open(this.map, e.target.getPosition());
    },
    // 将数组arr中的数据转换为指定格式
    transformArr(arr) {
      // 创建一个新的数组来存储转换后的数据
      const newArr = [];
      let activeTabArr = {};
      let tabArr = [];
      // 遍历arr中的每个元素
      for (let i = 0; i < arr.length; i++) {
        // 获取当前元素
        const item = arr[i];
        activeTabArr = {
          id: i,
          name: item.name,
          iconPath: item.iconPath,
          points: [
            {
              latitude: item.datas[0].latitude,
              longitude: item.datas[0].longitude
            }
          ]
        };

        // 将当前元素的id、iconPath、name和latitude添加到新的数组中
        newArr.push({
          tabID: i,
          id: Number(item.id.toString() + i.toString()),
          iconPath: item.iconPath || "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
          width: 20,
          height: 30,
          name: item.name,
          latitude: item.datas[0].latitude,
          longitude: item.datas[0].longitude,
          callout: {
            content: item.datas[0].title,
            text: item.datas[0].content,
            link: item.datas[0].link
          }
        });

        // 将当前元素的datas数组中的其他元素添加到新的数组中
        for (let j = 1; j < item.datas.length; j++) {
          newArr.push({
            tabID: i,
            id: Number(item.id.toString() + i.toString() + j.toString()),
            iconPath: item.iconPath || "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            width: 20,
            height: 30,
            name: item.name,
            latitude: item.datas[j].latitude,
            longitude: item.datas[j].longitude,
            callout: {
              content: item.datas[j].title,
              text: item.datas[j].content,
              link: item.datas[j].link
            }
          });
          activeTabArr.points.push({
            latitude: item.datas[j].latitude,
            longitude: item.datas[j].longitude
          });
        }
        tabArr.push(activeTabArr);
      }
      this.tabArr = tabArr;
      // 返回新的数组
      return newArr;
    },
    catchTap(e,index) {
      this.activeTab = index;
      let targetId = e.id;
      let _fitView = [];
      for (let i = 0; i < this.markers.length; i++) {
        // 获取存在每个 extData 中的 id
        let id = this.markers[i].getExtData().id;

        if (id === targetId) {
          _fitView.push(this.markers[i]);
        }
      }
      this.map.setFitView(_fitView);
      // let aaa = [[113.289432,23.110814],[113.307645,23.108015]]
      // this.map.setFitView(aaa)
      // let points = e.currentTarget.dataset.points || [];
      // let index = e.currentTarget.dataset.index;
      // this.setData({
      //   includePoints: points,
      //   activeTab: index,
      //   showCustomCallout: false
      // });
    }
  }
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .amap-icon img {
  width: 20px;
  height: 30px;
}
::v-deep .amap-marker-label {
  box-shadow: 0px 0px 4px 0px rgba(133, 133, 133, 0.5);
  border: none;
}

.cover-view {
  position: absolute;
  top: 3.125rem;
  left: 0.625rem;
  box-shadow: 0px 0px 4px 0px rgba(133, 133, 133, 0.5);
  /* opacity: .7; */
}

.flex-wrp {
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.85);
  border-radius: 4px;
}

.flex-item {
  display: flex;
  text-align: center;
  padding: 5px;
  font-size: 11px;
  flex-direction: column;
  align-items: center;
}
.activeTab {
  color: #fff;
  background-color: rgb(54, 115, 116);
}

.flex-item img {
  width: 25px;
}
.line-clamp-2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
::v-deep .btn-box {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}
::v-deep .btn-box .btn {
  width: 50px;
  text-align: center;
  line-height: 24px;
  background-color: rgb(54, 115, 116);
  border-radius: 12px;
  color: #fff;
  font-size: 11px;
}
</style>
